package common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Message implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7310427049134976396L;
	private String sender;
	public String receiver;
	protected byte[] data;
	private MessageType type;
	private TaskResult result;
	private String header;
	
	public byte[] toBytes() throws IOException
	{
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(output);
		out.writeObject(this);
		return output.toByteArray();
	}
	

	public Message(String sender, String receiver, MessageType Type,
			byte[] data) {
		header = "";
		type = Type;
		this.sender = sender;
		this.receiver = receiver;
		this.data = data;
		result = TaskResult.OK;
	}
	
	public static Message ParseFromBytes(byte[] data) throws ClassNotFoundException, IOException
	{
		Object o  =  new ObjectInputStream(new ByteArrayInputStream(data)).readObject();
		return (Message)o;
	}

	// / task result from message excute
	public TaskResult getTaskResult() {
		return result;
	}

	// /Set task result
	public void setTaskResult(TaskResult value) {
		result = value;
	}

	// / set content for message
	public void setData(byte[] data) {
		this.data = data;
	}

	// /set message type
	public void setMessageType(MessageType Type) {
		type = Type;
	}

	public void setReceiver(String Receiver) {
		receiver = Receiver;
	}

	// /set Sender
	public void setSender(String Sender) {
		sender = Sender;
	}

	// /get Message Type
	public MessageType getType() {
		return type;
	}

	public String getSender() {
		return sender;
	}

	public byte[] getContent() {
		return data;
	}

	public String getHeader()
	{
		return header;
	}
	
	public void setHeader(String header)
	{
		this.header = header;
	}

	public String getReceiver() {
		return receiver;
	}
}
